#include "trans.h"


//正式接收时使用小火车：buf = train.data，*flag = &train.flag
int recvFile(int sockfd,char* buf,int *flag){

    train_t train ;
    recv(sockfd,&train.flag,sizeof(train.flag),MSG_DONTWAIT);

    if(train.flag != GETS){
        perror("对应的命令不是GETS!");
    }
    //进入这里说明命令式GETS
    recv(sockfd,&train.length,sizeof(train.length),MSG_DONTWAIT);//接收数据长度字段
    recv(sockfd,train.data,train.length,MSG_DONTWAIT);//接收文件名
    char filename[4096] = {0};
    memcpy(filename,train.data,train.length);
    int filefd=open(filename,O_RDWR|O_CREAT|O_TRUNC,0666);

    //处理断点
    breakPoint_t breakPoint;

    int resume = load_breakpoint(filename,breakPoint);
    int break_resume_fd ;

    //load_breakpoint 的返回值为0时默认需要加载断点信息
    if(resume == 0){
        break_resume_fd = open(filename,O_RDWR,0666);
        if(break_resume_fd == -1){
            perror("打开文件失败，尝试从头开始！");
            break_resume_fd = open(filename,O_RDWR | O_CREAT | O_TRUNC,0666);
            resume = -1;//resume = -1 认为无法加载断点信息，只能重传
        }else{
            //找到断点位置
            lseek(break_resume_fd,breakPoint.offset,SEEK_SET);
            printf("从 %ld 位置开始续传！\n",breakPoint.offset);


            //将断点位置信息发送给对方
            train.length = sizeof(breakPoint.offset);
            memcpy(train.data,&breakPoint.offset,train.length);
            //还是先发头，告诉长度等信息
            send(sockfd,&train,sizeof(train.length)+sizeof(train.flag),0);
            //再发具体数据
            send(sockfd,&train.flag,sizeof(train.flag),0);
            send(sockfd,train.data,train.length,0);
        }

        close(break_resume_fd);

    }else{
        //直接从头开始发送，不涉及到续传

        off_t filesize;//定义变量存储文件总大小
        recv(sockfd,&train.length,sizeof(train.length),MSG_DONTWAIT);//接收文件大小字段的长度
        recv(sockfd,train.data,train.length,MSG_DONTWAIT);//接收文件大小数据

        memcpy(&filesize,train.data,sizeof(off_t));//将接收到的文件大小数据转换为off_t类型
        printf("filesize = %ld\n",filesize);

        while(1){//循环接收文件数据块并写入文件
            bzero(&train,sizeof(train));
            /* recv(sockfd,&train.flag,sizeof(train.flag),MSG_DONTWAIT);//非阻塞接收标志字段 */
            recv(sockfd,&train.length,sizeof(train.length),MSG_DONTWAIT);//接收当前数据块的长度
            if(train.length!=1000){
                printf("train.length = %d\n",train.length);
            }
            recv(sockfd,train.data,train.length,MSG_DONTWAIT);//接收当前数据块内容
            if(train.length==0){
                break;
            }
            write(filefd,train.data,train.length);//将数据块写入文件
        }
    }

    close(filefd);

    return 0;
}
